package com.johnsoft.pph;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.johnsoft.util.ZIP;

public class CabReader {
	
	DataInputStream cab;
	
	public CabReader() {
		try {
			cab = new DataInputStream(new FileInputStream(new File(Installer.setup.installFile)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		try {
			cab.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void unpack(String folder) throws IOException {
		new File(folder).mkdirs();
		while(cab.available() > 0) {
			Object[] file = readFile();
			File outFile = new File(folder + "\\" + file[0]);
			ZIP.createDirs(outFile.getAbsolutePath());
			System.out.println("Extracting: " + outFile.getAbsolutePath());
			DataOutputStream out = new DataOutputStream(new FileOutputStream(outFile));
			byte[] data = (byte[])file[1];
			out.write(data);
			out.close();
		}
	}
	
	public Object[] readFile() throws IOException {
		String filename = readString();
		int size = readInt();
		byte[] data = new byte[size];
		cab.read(data, 0, size);
		return new Object[] { filename, data };
	}
	
	public byte readByte() throws IOException {
		return cab.readByte();
	}
	
	public int readInt() throws IOException {
		return cab.readInt();
	}
	
	public String readString() throws IOException {
		short length = cab.readShort();
		String s = "";
		for(int i = 0; i < length; i++) {
			s += (char)readByte();
		}
		return s;
	}

}
